<template>
  <div class='container'>
    <el-dialog :title="`${data.id?'修改':'新增'}目录`" :visible.sync="dialogFormVisible" width="400px">
  <el-form :model="formModel" ref="form" :rules="rule" label-width="80px">

    <el-form-item label="所属学科" :label-width="formLabelWidth" >
      <el-select v-model="formModel.subjectID" style="width:100%" >
        <el-option
        v-for="item in subjectOptions"
        :label="item.label"
        :value="item.value"
        :key="item.value"></el-option>
      </el-select>
    </el-form-item>
     <el-form-item label="目录名称" :label-width="formLabelWidth">
      <el-input v-model="formModel.directoryName" ></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="close(form)">取 消</el-button>
    <el-button type="primary" @click="addDirectory" >确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import { simple as subjectList } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/directorys.js'
export default {
  name: 'DirectorysAdd',
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      formModel: {
        directoryName: '',
        subjectID: ''
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      rule: {
        subjectID: [
          { required: true, type: 'number', message: '请选择所属学科', tirgger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', tirgger: 'blur' }
        ]
      },
      subjectOptions: []
    }
  },
  async created () {
    const { data } = await subjectList()
    this.subjectOptions = data
    // console.log(data, 0)
  },
  methods: {
    addDirectory () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 提交
          if (!this.data.id) {
            // 新增
            await add(this.formModel)
          } else {
            // 修改
            this.formModel.id = this.data.id
            await update(this.formModel)
          }
          this.$message.success('操作成功')

          this.dialogFormVisible = false
          this.$emit('updateList')
        }
      })
    },
    open () {
      this.dialogFormVisible = true
      if (this.data.id) {
        const { id, subjectID, directoryName } = this.data
        this.formModel = { id, subjectID, directoryName }
      } else {
        this.formModel = {
          id: null,
          subjectID: +this.$route.query.id || null,
          directoryName: null
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    close (form) {
      this.dialogFormVisible = false
    }

  }
}
</script>
